import Vue from 'vue'
import Router from 'vue-router'
import { tokenManage } from 'utils/Cache'
import { getUa, test } from 'utils/utils'
import { weixinAuthorize } from 'api/thirdoauth'
import store from '@/store'

import pagesModules from './pagesModules' //主页
import accountModules from './accountModules' //账户相关
import orderModules from './orderModules' //订单相关
import marketingModules from './marketingModules' //营销相关
import walletModules from './walletModules' //钱包相关
import otherModules from './otherModules' //其他相关
import popularizeModules from './popularizeModules' //推广相关
import personalModules from './personalModules' //个人相关
import commonModules from './commonModules' //个人相关
import facilitatorModules from './facilitatorModules' //个人相关

const ErrorPage = () => import('views/ErrorPage/ErrorPage') //404

Vue.use(Router)

//解决编程式路由往同一地址跳转时会报错的情况
const originalPush = Router.prototype.push;
const originalReplace = Router.prototype.replace;
//push
Router.prototype.push = function push(location, onResolve, onReject) {
	if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject);
	return originalPush.call(this, location).catch(err => err);
};
//replace
Router.prototype.replace = function push(location, onResolve, onReject) {
	if (onResolve || onReject) return originalReplace.call(this, location, onResolve, onReject);
	return originalReplace.call(this, location).catch(err => err);
};

const router = new Router({
    mode: 'history', //如果是H5端：mode:'history'
    routes: [
        { path: '*', component: ErrorPage },
        {
            path: '/ErrorPage',
            component: ErrorPage,
            meta: {
                title: '404',
                keepAlive: true, //添加该字段，表示需要缓存
                showHeadBox: true, //显示HeadBox组件
                titleName: '404' //HeadBox组件中间显示的文字
            }
        },
        ...pagesModules,
        ...accountModules,
        ...orderModules,
        ...marketingModules,
        ...walletModules,
        ...otherModules,
        ...popularizeModules,
        ...personalModules,
        ...commonModules,
        ...facilitatorModules
    ],
    scrollBehavior(to, from, savedPosition) {
        if (savedPosition) {
            return savedPosition
        } else {
            return {
                x: 0,
                y: 0
            }
        }
    }
})

router.beforeEach(async (to, from, next) => {
    to.query.token && tokenManage.setToken(JSON.parse(to.query.token))
    to.query.liveSessionId && sessionStorage.setItem('LIVESESSIONID', to.query.liveSessionId)
    to.query.shopId && sessionStorage.setItem('SHOPID', to.query.shopId)

    if (to.matched.length === 0) {
        //如果未匹配到路由
        //如果上级也未匹配到路由则跳转首页，如果上级能匹配到则转上级路由
        from.name ? next({ name: from.name }) : next('/')
        return
    }

    // if (tokenManage.isLogin()) {
    //     //如果已登录去登录页 直接返回首页
    //     if (to.path == '/login') {
    //         router.push({
    //             path: '/index'
    //         })
    //         return
    //     }
    // }


    //如果需要登录 往下走
    if (to.meta.requireAuth) {
        // 如果没有登录过  就去登录
        if (!tokenManage.isLogin()) {
            if (getUa().isWeixin && store.state.enableWeixinLogin) {
                // 前往平台微信公众号网页授权
                weixinAuthorize(to.fullPath)
                return
            }

            router.replace({
                path: '/login',
                query: { redirect: to.fullPath }
            })
            return
        } else { //如果没有登录
			//如果没有完善信息 则转到完善信息界面
			if(test.isEmpty(store.state.curUpInfo)) await store.dispatch('setupInfo');
			let { result } = store.state.curUpInfo
			if(result && ['my', 'submitOrder'].includes(to.name)) router.replace({ name: 'security', query: { need: 'finish', redirect: to.query.redirect } })
		}
    }

    //不需要跳转，直接往下走
    next()
})
export default router
